package com.ravi.core.queue;

import com.ravi.core.patient.BasePatient;
import com.ravi.core.patient.IPatient;
import com.ravi.entity.CheckRoom;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Data
public class CheckUpQueue {
	private AtomicInteger mAtomicInteger = new AtomicInteger();

	private final BlockingQueue<BasePatient> mCheckQueue = new PriorityBlockingQueue<>();

	private CheckRoom checkRoom;

	public CheckUpQueue(CheckRoom checkRoom) {
		this.checkRoom = checkRoom;
	}

	/**
	 * 插入时 因为每一个Patient都实现了comparable接口 所以队列会按照Patient复写的compare()方法定义的优先级次序进行插入
	 * 当优先级相同时，使用AtomicInteger原子类自增 来为每一个task 设置sequence
	 * <b>sequence</b>的作用是标记两个相同优先级的任务入队的次序
	 * @see BasePatient#compareTo(IPatient)
	 */
	public <T extends BasePatient> int add(T patient) {
		if (!mCheckQueue.contains(patient)) {
			patient.setSequence(mAtomicInteger.incrementAndGet());
			mCheckQueue.add(patient);
			log.info(checkRoom.getRoomName() + "\n");
		}
		return mCheckQueue.size();
	}
	public <T extends BasePatient> void remove(T patient){
		if (mCheckQueue.contains(patient)) {
			mCheckQueue.remove(patient);
		}
	}

	// 出队，无元素则返回null
	public BasePatient poll() {
		return mCheckQueue.poll();
	}

	// 出队，无元素则waiting
	public BasePatient take () throws InterruptedException{
		return mCheckQueue.take();
	}

	public void clear(){
		mCheckQueue.clear();
	}

	public int size(){
		return mCheckQueue.size();
	}

	public boolean isContain(BasePatient patient) {
		return mCheckQueue.contains(patient);
	}

}
